// 2pages/login/login.js
let app = getApp();
import { registerApi,loginApi } from "../../api/index.js";
let timeId = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    paddingTop: app.globalData.paddingTop,
    accoun: "",
    passWd: "",
    code: "",
    passwordHidden: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let token = wx.getStorageSync("token");
    if (token) {
      wx.redirectTo({
        url: "/pages/index/index",
      });
      return;
    }
  },
  onUnload() {
    clearTimeout(timeId);
  },
  /**
   * 获取用户名
   * @param {object} event
   */
  getUserName(e) {
    let val = e.detail.value;
    // 使用正则表达式校验账号格式
    if (!/^[0-9a-zA-Z]{0,11}$/.test(val)) {
      // 如果输入不符合规定，则清空输入框中的内容
      this.setData({
        accoun: "",
      });
      wx.showToast({
        title: "账号格式错误",
        icon: "none",
      });
      return;
    }
    this.setData({
      accoun: val,
    });
  },

  getPassWd(e) {
    let val = e.detail.value;
    // 使用正则表达式校验密码格式
    if (!/^[0-9a-zA-Z]{0,30}$/.test(val)) {
      // 如果输入不符合规定，则清空输入框中的内容
      this.setData({
        passWd: "",
      });
      wx.showToast({
        title: "密码格式错误",
        icon: "none",
      });
      return;
    }
    this.setData({
      passWd: val,
    });
  },

  //   注册
  async bindRegistered() {
    const { accoun, passWd } = this.data;
    if (!accoun) {
      getApp().showToast("请输入账号");
      return;
    }
    if (!passWd) {
      getApp().showToast("请输入密码");
      return;
    }
    try {
      await registerApi({ accoun, passWd });
      wx.setStorageSync("accoun", accoun);
      wx.setStorageSync("passWd", passWd);
      getApp().showToast("注册成功,请登录");
      // timeId = setTimeout(() => {
      //   wx.navigateBack({ delta: 1 });
      // }, 500);
    } catch (error) {
      getApp().showToast(error.data.desc);
      // console.log(error);
    }
  },

  // 查看密码
  togglePasswordVisibility() {
    console.log(this.data.passwordHidden);
    this.setData({
      passwordHidden: !this.data.passwordHidden,
    });
  },

  // 登录
  async bindLogin() {
    const { accoun, passWd } = this.data;
    if (!accoun) {
      getApp().showToast("请输入账号");
      return;
    }
    if (!passWd) {
      getApp().showToast("请输入密码");
      return;
    }
    try {
      const { data: res } = await loginApi({ accoun, passWd });
      console.log(res);
      const { token, userId, parkId } = res.data;
      console.log(userId, "userId");
      wx.setStorageSync("token", token);
      wx.setStorageSync("userId", userId);
      wx.setStorageSync("parkId", parkId);
      wx.setStorageSync("accoun", accoun);
      getApp().showToast("登录成功");
      timeId = setTimeout(() => {
        wx.switchTab({
          url: "/pages/index/index",
        });
      }, 1000);
    } catch (error) {
      console.log(error);
      getApp().showToast(error.data.desc);
    }
  },
});
